package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.user.*;
import com.SmartCampus.system.model.entity.Clazz;
import com.SmartCampus.system.model.entity.User;
import com.SmartCampus.system.model.vo.LoginUserVO;
import com.SmartCampus.system.model.vo.UserVO;
import com.SmartCampus.system.service.ClazzService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.SmartCampus.system.constant.UserConstant.SALT;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private ClazzService clazzService;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest,
            HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(user);

        if (user.getClazzId() != 0) {
            QueryWrapper<Clazz> queryClazz = new QueryWrapper<>();
            queryClazz.eq("id", user.getClazzId());
            if (clazzService.count(queryClazz) == 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级不存在");
            }
            Clazz clazz = clazzService.getOne(queryClazz);
            loginUserVO.setClazzName(clazz.getName());
        } else {
            loginUserVO.setClazzName("未知");
        }

        return ResultUtils.success(loginUserVO);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户（仅管理员)
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "添加用户（仅管理员)")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        user.setPassword("28d9a61fec4fc4e01b5dd65b29c00812");
        user.setUserAvatar("http://39.98.107.158:9000/photo/1732267182363_a14893c3ce4f48d2867cbd712a34d125.png");
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户（仅管理员)
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除用户（仅管理员)")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户（仅管理员)
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新用户（仅管理员)")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 通过id查找用户
        User oldUser = userService.getById(userUpdateRequest.getId());
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 如果没有提供新的userAccount，则使用原来的
        if (userUpdateRequest.getUserAccount() == null || userUpdateRequest.getUserAccount().equals("")) {
            userUpdateRequest.setUserAccount(oldUser.getUserAccount());
        }

        // 同理，处理其他字段
        if (userUpdateRequest.getPassword() == null || userUpdateRequest.getPassword().equals("")) {
            userUpdateRequest.setPassword(oldUser.getPassword());
        }

        if (userUpdateRequest.getUsername() == null || userUpdateRequest.getUsername().equals("")) {
            userUpdateRequest.setUsername(oldUser.getUsername());
        }

        if (userUpdateRequest.getTelephone() == null || userUpdateRequest.getTelephone().equals("")) {
            userUpdateRequest.setTelephone(oldUser.getTelephone());
        }

        if (userUpdateRequest.getAddress() == null || userUpdateRequest.getAddress().equals("")) {
            userUpdateRequest.setAddress(oldUser.getAddress());
        }

        if (userUpdateRequest.getUserProfile() == null || userUpdateRequest.getUserProfile().equals("")) {
            userUpdateRequest.setUserProfile(oldUser.getUserProfile());
        }

        // 处理班级信息
        if (userUpdateRequest.getClazzName() != null && !userUpdateRequest.getClazzName().equals("")) {
            Clazz oldClazz = clazzService
                    .getOne(new QueryWrapper<Clazz>().eq("name", userUpdateRequest.getClazzName()));
            if (oldClazz == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "班级不存在，请检查clazzName是否正确");
            }
            oldUser.setClazzId(oldClazz.getId());
        }

        // 使用BeanUtils复制属性
        BeanUtils.copyProperties(userUpdateRequest, oldUser);

        // 更新用户信息
        boolean result = userService.updateById(oldUser);

        // 如果更新失败，抛出操作错误
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/get")
    @ApiOperation(value = "根据 id 获取用户")
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取用户列表")
    public BaseResponse<Page<UserVO>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        long current = userQueryRequest.getCurrent() == 0 ? 1 : userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize() == 0 ? 10 : userQueryRequest.getPageSize();
        Page<UserVO> pageParam = new Page<>(current, size);
        Page<UserVO> userPage = userService.pageByAll(pageParam, userQueryRequest);
        return ResultUtils.success(userPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    @ApiOperation(value = "更新个人信息")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", loginUser.getId());
        User user = userService.getOne(queryWrapper);
        if (userUpdateMyRequest.getUserAccount() == null || userUpdateMyRequest.getUserAccount().equals("")) {
            userUpdateMyRequest.setUserAccount(user.getUserAccount());
        }
        if (userUpdateMyRequest.getPassword() == null || userUpdateMyRequest.getPassword().equals("")) {
            userUpdateMyRequest.setPassword(user.getPassword());
        } else {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userUpdateMyRequest.getPassword()).getBytes());
            user.setPassword(encryptPassword);
        }
        if (userUpdateMyRequest.getUsername() == null || userUpdateMyRequest.getUsername().equals("")) {
            userUpdateMyRequest.setUsername(user.getUsername());
        }
        if (userUpdateMyRequest.getTelephone() == null || userUpdateMyRequest.getTelephone().equals("")) {
            userUpdateMyRequest.setTelephone(user.getTelephone());
        }
        if (userUpdateMyRequest.getAddress() == null || userUpdateMyRequest.getAddress().equals("")) {
            userUpdateMyRequest.setAddress(user.getAddress());
        }
        if (userUpdateMyRequest.getUserAvatar() == null || userUpdateMyRequest.getUserAvatar().equals("")) {
            userUpdateMyRequest.setUserAvatar(user.getUserAvatar());
        }
        if (userUpdateMyRequest.getUserProfile() == null || userUpdateMyRequest.getUserProfile().equals("")) {
            userUpdateMyRequest.setUserProfile(user.getUserProfile());
        }
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取所有管理员列表
     *
     * @return
     */
    @PostMapping("/list/admin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "获取所有管理员列表（仅管理员）")
    public BaseResponse<List<UserVO>> listAdminUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userRole", UserConstant.ADMIN_ROLE);
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> userVOList = userList.stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                })
                .collect(Collectors.toList());
        return ResultUtils.success(userVOList);
    }

    /**
     * 获取所有教师列表
     *
     * @return
     */
    @PostMapping("/list/teacher")
    @ApiOperation(value = "获取所有教师列表")
    public BaseResponse<List<UserVO>> listTeacherUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userRole", UserConstant.TEACHER_ROLE);
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> userVOList = userList.stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                })
                .collect(Collectors.toList());
        return ResultUtils.success(userVOList);
    }
}
